package com.decent.core.alarm.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;

/**
 * 通用Server validation方法
 *
 * @author menghx
 * @date 2022-2-18 14:05:04
 */
@Component
public class Validators {
    @Resource
    private Validator validator;

    /**
     * 验证实体
     *
     * @param obj 实体
     * @param <T> 实体类类型
     * @return 结果
     */
    @SuppressWarnings("unused")
    public <T> String valid(T obj) {
        return this.valid(obj, (Class<?>) null);
    }


    /**
     * 验证实体
     *
     * @param obj   实体
     * @param group 实体组
     * @param <T>   实体类类型数组
     * @return 结果
     */
    public <T> String valid(T obj, Class<?>... group) {
        Set<ConstraintViolation<T>> violations;
        if (ArrayUtil.isEmpty(group)) {
            violations = validator.validate(obj);
        } else {
            violations = validator.validate(obj, group);
        }
        if (CollectionUtils.isNotEmpty(violations)) {
            for (ConstraintViolation<T> constraintViolation : violations) {
                return constraintViolation.getMessage();
            }
        }
        return null;
    }

    /**
     * 校验list
     *
     * @param objList list
     * @param <T>     实体类类型
     * @return 结果
     */
    @SuppressWarnings("unused")
    public <T> String validList(List<T> objList) {
        return this.validList(objList, null);
    }

    /**
     * 校验list
     *
     * @param objList list
     * @param group   组
     * @param <T>     实体类类型
     * @return 结果
     */
    public <T> String validList(List<T> objList, Class<?> group) {
        if (CollectionUtils.isEmpty(objList) || objList.size() <= 0) {
            return "对象空";
        }
        String result;
        for (T t : objList) {
            if (group == null) {
                result = this.valid(t);
            } else {
                result = this.valid(t, group);
            }
            if (StrUtil.isNotBlank(result)) {
                return result;
            }
        }
        return null;
    }
}
